package com.czk.aop;

import com.alibaba.fastjson.JSON;
import com.czk.anotation.OperateLog;
import com.czk.feign.OperateLogFeign;
import com.czk.model.TbOperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/10/21 16:02
 */
@Aspect
@Component
public class OperateAdvice {
    @Autowired
    private OperateLogFeign operateLogFeign;

    @Around("execution(* com.czk.controller.*.*(..)) && @annotation(operateLog)")
    public Object insertLogAround(ProceedingJoinPoint pjp, OperateLog operateLog) throws Throwable {
        System.out.println(" *********************************** 记录日志 [start]  ****************************** ");

        TbOperateLog op = new TbOperateLog();

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        op.setOperateTime(sdf.format(new Date()));
        op.setOperateUser("10000");
        // 哪个类
        op.setOperateClass(pjp.getTarget().getClass().getName());
        // 哪个方法
        op.setOperateMethod(pjp.getSignature().getName());

        String paramAndValue = "";
        Object[] args = pjp.getArgs();
        if (args != null) {
            for (Object arg : args) {
                // 基本参数类型
                if (arg instanceof String || arg instanceof Integer || arg instanceof Long) {
                    paramAndValue += arg + ",";
                } else {
                    // 复杂类型转为string
                    paramAndValue += JSON.toJSONString(arg) + ",";
                }
            }
            op.setParamAndValue(paramAndValue);
        }

        long start_time = System.currentTimeMillis();

        // 放行
        Object object = pjp.proceed();

        long end_time = System.currentTimeMillis();
        op.setCostTime(end_time - start_time);

        if (object != null) {
            op.setReturnClass(object.getClass().getName());
            op.setReturnValue(object.toString());
        } else {
            op.setReturnClass("java.lang.Object");
            op.setParamAndValue("void");
        }
        // feign远程调用
        operateLogFeign.add(op);

        System.out.println(" *********************************** 记录日志 [end]  ****************************** ");

        return object;
    }
}
